package com.ruoyi.apiserver.services;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.apiserver.config.ReportGenerationMQConfig;
import com.ruoyi.apiserver.services.impl.CozeServices;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.members.domain.MhUser;
import com.ruoyi.members.service.IMhUserService;
import com.ruoyi.mhorders.domain.MhOrder;
import com.ruoyi.mhorders.service.IMhOrderService;
import com.ruoyi.test.domain.MhTest;
import com.ruoyi.test.domain.MhTestMore;
import com.ruoyi.test.service.IMhTestMoreService;
import com.ruoyi.test.service.IMhTestService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class ReportGenerationConsumerService {

    @Autowired
    private CozeServices cozeServices;

    @Autowired
    private IMhTestService mhTestService;

    @Autowired
    private IMhOrderService mhOrderService;

    @Autowired
    private IMhTestMoreService mhTestMoreService;

    @Autowired
    private IMhUserService mhUserService;

    /**
     * 监听并处理报告生成请求消息
     *
     * @param message 消息内容
     */
    @RabbitListener(queues = ReportGenerationMQConfig.REPORT_GENERATION_QUEUE)
    public void handleReportGenerationRequest(Map<String, Object> message) {
        try {
            System.out.println("接收到报告生成请求消息: " + message);

            // 从消息中获取参数
            String outTradeNo = (String) message.get("outTradeNo");
            Long userId = ((Number) message.get("userId")).longValue();

            // 检查必要参数
            if (StringUtils.isEmpty(outTradeNo) || userId == null) {
                System.err.println("报告生成请求参数不完整: outTradeNo=" + outTradeNo + ", userId=" + userId);
                return;
            }

            // 获取订单信息
            MhOrder mhOrder = mhOrderService.selectMhOrderByOrderNO(outTradeNo);
            if (mhOrder == null) {
                System.err.println("报告生成订单获取为空！: outTradeNo=" + outTradeNo + ", userId=" + userId);
                return;
            }

            // 获取测试信息
            MhTest mhTest = mhTestService.selectMhTestById(mhOrder.getProductId());
            if (mhTest == null) {
                System.err.println("报告生成mhTest获取为空！: outTradeNo=" + outTradeNo + ", userId=" + userId);
                return;
            }

            // 获取用户信息
            MhUser mhUser = mhUserService.selectMhUserById(userId);
            if (mhUser == null) {
                System.err.println("报告生成用户获取为空！: outTradeNo=" + outTradeNo + ", userId=" + userId);
                return;
            }

            String queryJson = "我的测试结果是" + mhTest.getTestResult() + "，测试原始值：" + mhTest.getTestValue();

            Map<String, Object> result = cozeServices.getJSON(queryJson);
            
            // 检查result是否为空
            if (result == null || result.isEmpty()) {
                System.err.println("报告生成结果为空！: outTradeNo=" + outTradeNo + ", userId=" + userId);
                return;
            }
            
            //保存到数据库
            int Count = 0;
            long index = 1L;
            for (Map.Entry<String, Object> entry : result.entrySet()) {
                System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
                MhTestMore mhTestMore = new MhTestMore();
                mhTestMore.setKey(entry.getKey());
                // 将entry.getValue()序列化为JSON字符串
                String jsonValue = serializeToJson(entry.getValue());
                mhTestMore.setJsonValue(jsonValue);
                mhTestMore.setUserId(userId);
                mhTestMore.setTestId(mhTest.getId());
                mhTestMore.setOrderNo(mhOrder.getOrderNo());
                mhTestMore.setSort(index);
                mhTestMore.setIsEncrypted(1L);
                index++;
                Count += mhTestMoreService.insertMhTestMore(mhTestMore);
            }

            if (Count <= 0 || Count != result.size()) {
                System.err.println("报告生成，保存失败/数据不完整！: outTradeNo=" + outTradeNo + ", userId=" + userId);
                return;
            }
            System.out.println("报告生成结果: " + result);

            System.out.println("报告生成完成，订单号: " + outTradeNo + ", 用户ID: " + userId);

        } catch (Exception e) {
            System.err.println("处理报告生成请求时发生错误: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 确保方法总是能够正常结束
            System.out.println("报告生成请求处理完毕");
        }
    }

    /**
     * 将对象序列化为JSON字符串
     *
     * @param obj 要序列化的对象
     * @return JSON字符串
     */
    private String serializeToJson(Object obj) {
        if (obj == null) {
            return "";
        }

        try {
            // 如果对象本身就是字符串，直接返回
            if (obj instanceof String) {
                return (String) obj;
            }

            // 使用Jackson ObjectMapper序列化
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            // 如果Jackson序列化失败，尝试使用Hutool的JSONUtil
            try {
                return JSONUtil.toJsonStr(obj);
            } catch (Exception ex) {
                // 如果两种方式都失败，返回对象的toString()结果
                return obj.toString();
            }
        }
    }
}